package com.example.controller;

import com.example.common.Result;
import com.example.entity.SensitiveWord;
import com.example.service.SensitiveWordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sensitive-word")
public class SensitiveWordController {

    @Resource
    private SensitiveWordService sensitiveWordService;

    @PostMapping("/add")
    public Result add(@RequestBody SensitiveWord sensitiveWord) {
        sensitiveWordService.addSensitiveWord(sensitiveWord);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        sensitiveWordService.deleteSensitiveWord(id);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody SensitiveWord sensitiveWord) {
        sensitiveWordService.updateSensitiveWord(sensitiveWord);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<SensitiveWord> list = sensitiveWordService.getAllSensitiveWords();
        return Result.success(list);
    }

    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(required = false) String word) {
        PageHelper.startPage(pageNum, pageSize);
        List<SensitiveWord> list = sensitiveWordService.getAllSensitiveWords();
        if (word != null && !word.isEmpty()) {
            list = list.stream()
                    .filter(w -> w.getWord().contains(word))
                    .collect(Collectors.toList());
        }
        PageInfo<SensitiveWord> pageInfo = PageInfo.of(list);
        return Result.success(pageInfo);
    }

}